package com.th.apicenter.wph.service.impl;


import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.th.apicenter.mapper.ThWphOrdersMapper;
import com.th.apicenter.wph.ThWphOrders;

import com.th.apicenter.wph.service.ThWphOrdersService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;


import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 *
 */
@Service
@Slf4j
public class ThWphOrdersServiceImpl extends ServiceImpl<ThWphOrdersMapper, ThWphOrders>
    implements ThWphOrdersService {

    //appkey：6i7qk77le0vq4dvg
    //appsecret：a94i039wxo2d0xs9dq6hgz71lznpl7gd
    static final String APP_KEY ="6i7qk77le0vq4dvg";
    static final String APP_SECRET ="a94i039wxo2d0xs9dq6hgz71lznpl7gd";
    static final String HW_APP_SECRET="GoM90QYmlFSToxi4V6DLK9v4Grd4K8AU+68G0iF0OJM=";



    @Override
    public void orderQuery(int page, long startTime, long endTime, int type, String openId, String channelTag, String status) {

        // 1. 构建基础参数
        // 1. 构建基础参数（包括timestamp）
        Map<String, String> params = new LinkedHashMap<>();
        params.put("appkey",APP_KEY);
        long timestamp  = System.currentTimeMillis() / 1000;
        params.put("timestamp", Long.toString(timestamp));
        params.put("page",String.valueOf(page));
        params.put("startTime",String.valueOf(startTime));
        params.put("endTime",String.valueOf(endTime));
        params.put("type",String.valueOf(type));
        params.put("openId",String.valueOf(openId));
        params.put("channelTag",String.valueOf(channelTag));
        params.put("status",String.valueOf(status));
        // 2. 生成签名（传入appSecret）
        String sign = generateMD5Sign(params, APP_SECRET);
        params.put("sign", sign);
        String body = JSON.toJSONString(params);

        // 3. 设置请求头
        HttpRequest request = HttpUtil.createPost("https://gylmsturl.gylm2020.com/gylmJ/api/v1/wphcomm/orderList"); // 替换为真实URL
        request.header("Content-Type", "application/json;charset=UTF-8");
        request.header("Accept", "application/json");
        request.timeout(5000); // 设置超时时间为5秒（连接+读取超时）
        request.body(body);//设置请求参数内容
        //发送请求
        String result = request.execute().body();
        log.info("唯品会订单数据返回："+result);

    }

    @Override
    public void hwOCPCOrders(String orderId, String conversionType, String callbackUrl, String timestamp, String conversionTime) {
        // 1. 构建基础参数
        // 1. 构建基础参数（包括timestamp）
        Map<String, Object> params = new LinkedHashMap<>();
        //必填
        params.put("conversion_type",conversionType);
        params.put("callback", callbackUrl);
        params.put("timestamp",timestamp);
        params.put("conversion_time",conversionTime);
//        //非必填
//        Map<String, Object> extend = new HashMap<>();
//        extend.put("revenue", amount);
//        extend.put("currency", "CNY");
//        extend.put("order_id", orderId);
//
//        params.put("conversion_extend", extend);
//        params.put("order_id",orderId);
        String body = JSON.toJSONString(params);
        // 2. 生成签名（传入appSecret）
        String authorization = generateAuthorizationHeader(body, HW_APP_SECRET);

        // 3. 设置请求头
        HttpRequest request = HttpUtil.createPost("https://gylmsturl.gylm2020.com/gylmJ/api/v1/wphcomm/orderList"); // 替换为真实URL
        request.header("Content-Type", "application/json;charset=UTF-8");
        request.header("Accept", "application/json");
        request.header("sign", authorization);
        request.timeout(5000); // 设置超时时间为5秒（连接+读取超时）
        request.body(body);//设置请求参数内容
        //发送请求
        String result = request.execute().body();
        log.info("华为OCPC回传数据返回："+result);
    }


    // 修正后的签名生成方法
    public static String generateAuthorizationHeader(String requestBody, String secretKey) {
        try {
            // 1. 获取当前时间戳
            long currentTimeMillis = System.currentTimeMillis();

            // 2. 配置HMAC-SHA256签名
            Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
            SecretKeySpec secret_key = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8),
                    "HmacSHA256");
            sha256_HMAC.init(secret_key);

            // 3. 计算签名
            byte[] signatureBytes = sha256_HMAC.doFinal(requestBody.getBytes(StandardCharsets.UTF_8));
            String signature = Hex.encodeHexString(signatureBytes);

            // 4. 构建正确的Authorization头
            return String.format("Digest validTime=\"%d\", response=\"%s\"",
                    currentTimeMillis, signature);
        } catch (Exception e) {
            throw new RuntimeException("生成华为OCPC签名失败", e);
        }
    }



    /**
     * 生成唯品会API的MD5签名
     * @param params 请求参数（需包含appKey、timestamp等系统参数）
     * @param appSecret 开发者密钥
     * @return 大写MD5签名
     */
    public static String generateMD5Sign(Map<String, String> params, String appSecret) {
        // 1. 参数按字母升序排序
        Map<String, String> sortedParams = new TreeMap<>(params);

        // 2. 拼接参数字符串（格式：key1value1key2value2...）
        StringBuilder signStr = new StringBuilder();
        for (Map.Entry<String, String> entry : sortedParams.entrySet()) {
            signStr.append(entry.getKey()).append(entry.getValue());
        }

        // 3. 前后拼接AppSecret并进行MD5加密
        String fullStr = appSecret + signStr.toString() + appSecret;
        return DigestUtils.md5Hex(fullStr).toUpperCase();
    }
}




